import Flutter
import UIKit

public class SwiftKwPayPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "kw_pay", binaryMessenger: registrar.messenger())
    let instance = SwiftKwPayPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
    registrar.addApplicationDelegate(instance)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "pay":
        handlerPay(call.arguments, result)
    default:
        break
    }
  }
    
    private var flutterResult:FlutterResult?
    
    private func handlerPay(_ params:Any?,_ result: FlutterResult?){
        guard let p = params as? [String:Any] else {
            return
        }
        guard let type = p["type"] as? String else { return }
        guard let tn = p["orderId"] as? String else { return }
        guard let mode = p["mode"] as? String else {
            return
        }
        print(type,tn,mode)
        switch type {
            case "upPay":
                
                if UPPaymentControl.default().isPaymentAppInstalled(){
                    flutterResult = result
                    UPPaymentControl.default().startPay(tn, fromScheme: "xingda", mode: mode == "dev" ? "01" : "00", viewController: UIApplication.shared.delegate?.window??.rootViewController)
                }else{
                    result?(["result":"fail"])
                }
                
                break
            default:
                break

        }
    }
    
    public func applicationDidBecomeActive(_ application: UIApplication) {
        
    }
    
    public func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        UPPaymentControl.default().handlePaymentResult(url) {[weak self] code, data in
            print(code,data)
            self?.flutterResult?(["result":code,"data":data])
        }
        return true
    }
    
    public func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        UPPaymentControl.default().handlePaymentResult(url) {[weak self] code, data in
            print(code,data)
            self?.flutterResult?(["result":code,"data":data])
        }
        return true
    }
}
